<?php

namespace app\admin\controller\wanlshop;

use addons\wanlshop\library\WanlChat\WanlChat;
use addons\ymyauexpress\library\Express;
use addons\ymyauexpress\library\Expressty;
use addons\ymyauexpress\library\Expressyt;
use app\common\controller\Backend;
use app\common\library\QueueApi;
use think\Cache;
use think\Db;
use think\Exception;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Package extends Backend
{
    /**
     * Package模型对象
     * @var \app\admin\model\wanlshop\Package
     */
    protected $model = null;
    protected $wanlchat = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->wanlchat = new WanlChat();
        $this->model = new \app\admin\model\wanlshop\Package;
        $this->view->assign("deliveryModeList", $this->model->getDeliveryModeList());
        $this->view->assign("idcardStatusList", $this->model->getIdcardStatusList());
        $this->view->assign("deliveryStatusList", $this->model->getDeliveryStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['wanlshoporder','user','wanlshopshop'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('wanlshoporder')->visible(['order_no']);
				$row->getRelation('user')->visible(['nickname','avatar','mobile']);
				$row->getRelation('wanlshopshop')->visible(['shopname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function detail($ids = null){
        $multi = $this->request->param('multi','');
        if($multi == 'order'){
            $list = $this->model
                ->with(['wanlshoporder','user','wanlshopshop','goods'])
                ->whereIn('package.order_id',$ids)
                ->select();
        }else{
            $list = $this->model
                ->with(['wanlshoporder','user','wanlshopshop','goods'])
                ->whereIn('package.id',$ids)
                ->select();
        }

        foreach ($list as $row){
            $row->getRelation('wanlshoporder')->visible(['order_no']);
            $row->getRelation('user')->visible(['nickname','avatar','mobile']);
            $row->getRelation('wanlshopshop')->visible(['shopname']);
            $row['address'] = model('app\admin\model\wanlshop\Packageaddress')
                ->where(['package_id' => $row['id']])
                ->order('isaddress desc')
                ->find();
            $row['freight'] = model('app\api\model\wanlshop\ShopFreight')->where('id', $row['freight_id'])->find();
        }
        $list = collection($list)->toArray();
        $this->view->assign('list',$list);
        return $this->view->fetch();
    }

    // 上传客户身份证
    public function uploadIdcard(){
        if($this->request->isPost()){
            $package_id = $this->request->post('package_id');
            $package_id ? $package_id : ($this->error(__('非法请求')));
            $package = model('app\admin\model\wanlshop\Package')->get($package_id,['goods']);
            if($package['delivery_status'] == 0){
                $this->error('该包裹还未发货');
            }
            QueueApi::auUploadIdcard([
                'id' => $package_id,
                'shop_id' => $this->shop->id,
                'express_no' => $package['express_no'],
            ],5);
            $this->success(__('上传成功,数据异步传输,请等待10秒左右刷新查看状态'));
        }
    }

    // 发货 & 批量发货
    public function delivery($ids = null){
        $config = get_addon_config('ymyauexpress');
        if(!$config['au_member_id'] || !$config['au_password']){
            $this->error('请先配置澳邮参数');
        }
        $express = new Express($config['au_member_id'],$config['au_password']);
        $brands = Cache::get($config['au_member_id'].'brands') ?? [];
        if(empty($brands)){
            $brands = $express->brand();
            Cache::set($config['au_member_id'].'brands',$brands,86400);
        }
        $data = [];
        $lists = [];
        $row = $this->model->all($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        foreach ($row as $vo) {

            $vo['address'] = model('app\admin\model\wanlshop\Packageaddress')
                ->where(['package_id' => $vo['id']])
                ->order('isaddress desc')
                ->find();
            if ($vo['delivery_status'] == 0 && $vo['delivery_mode'] == 'instead') {
                $lists[] = $vo;
            } else {
                $data[] = $vo;
            }
        }
        if ($this->request->isAjax()) {
            $request = $this->request->post();
            if (!array_key_exists("order", $request['row'])) {
                $this->success(__('没有发现可以发货订单~'));
            }
            if(!$this->wanlchat->isWsStart()){
                $this->error('平台未启动IM即时通讯服务，暂时不可以发货');
            }
            $packageAll = [];
            $orderAll = [];
            $e = new Expressty();
            foreach ($request['row']['order']['id'] as $key => $id) {
                try{
                    $package = model('app\admin\model\wanlshop\Package')->get($id,['goods']);
                    $address = model('app\admin\model\wanlshop\Packageaddress')
                        ->where(['package_id' => $id, 'shop_id' => $package['shop_id']])
                        ->order('isaddress desc')
                        ->field('id,name,mobile,address,address_name,number,image_front,image_back')
                        ->find();
                    $f = Db::name('wanlshop_shop_freight')->where('id',$package->freight_id)->value('type');
                    if($f=='yt'){

                        $orderno = Db::name('wanlshop_order')->where('id',$package['order_id'])->value('order_no');
                        $shopConfig = model('app\api\model\wanlshop\ShopConfig')->where('shop_id',$package['shop_id'])->find();

                        $addressDetail = explode('/',$address['address']);
                        $d = array();
                        foreach ($package['goods'] as $value){
                            $brand_id = Db::name('wanlshop_goods')->where('id',$value['goods_id'])->value('brand_id');
                            $brand_name = Db::name('wanlshop_brand')->where('id',$brand_id)->value('name');
                            $d[]=[
                                'code'=>$value['goods_sku_sn'],
                                "num"=> $value['number'],
                                "brand"=> empty($brand_name)?"默认":$brand_name,
                                "name"=> $value['title'],
                                "specs"=> "默认",
                                "unit"=> "默认",
                                "weight"=> $value['weight'],
                            ];
                        }

                        $er = $e->create([
                            'orderno'=>$orderno,
                            "sendername"=> $shopConfig['sendName'],
                            "senderphone"=> $shopConfig['sendPhoneNum'],
                            "receiptname"=> $address['name'],
                            "receiptphone"=> $address['mobile'],
                            "idcard"=> $address['number'],
                            "receiptprovince"=> $addressDetail[0],
                            "receiptcity"=> $addressDetail[1],
                            "receiptarea"=> $addressDetail[2],
                            "receiptaddress"=> $address['address_name'],
                            "line"=> "2",
                            "datalist"=>$d
                        ]);


                        if(!is_array($er)){
                            $er = json_decode($er,true);
                        }

                        if($er['code']=='1' or $er['code']=='-2'){
                            $express_no = $er['logisticsno'];

                            $packageAll[] = [
                                'id' => $id,
                                'express_name' => '圆通国际',
                                'express_no' => $express_no,
                                'delivertime' => time(),
                                'delivery_status' => 1
                            ];
                            $orderAll[] = [
                                'id' => $package['order_id'],
                                'delivertime' => time(),
                                'state' => 3
                            ];

                            QueueApi::auUploadIdcard([
                                'id' => $id,
                                'shop_id' => $package['shop_id'],
                                'express_no' => $express_no,
                            ],5);
                            QueueApi::auPrint([
                                'id' => $id,
                                'shop_id' => $package['shop_id'],
                            ],5);
                            // 推送消息
                            $this->pushOrder($id,'已发货');

                        }

                    }elseif ($f=='au'){

                        $addressDetail = explode('/',$address['address']);
                        $ShipmentContent = '';
                        foreach ($package['goods'] as $goods){
                            $ShipmentContent .= $goods['title'].'*'.$goods['number'].';';
                        }
                        $shopConfig = model('app\api\model\wanlshop\ShopConfig')->where('shop_id',$package['shop_id'])->find();
                        $params = [
                            "BrandID"=> $request['row']['BrandId'],
                            "SenderName"=> $shopConfig['sendName'],
                            "SenderPhone"=> $shopConfig['sendPhoneNum'],
                            "ReceiverName"=> $address['name'],
                            "ReceiverPhone"=> $address['mobile'],
                            "ReceiverProvince"=> $addressDetail[0],
                            "ReceiverCity"=> $addressDetail[1],
                            "ReceiverAddr1"=> $addressDetail[2].$addressDetail[3].$address['address_name'],
                            "ShipmentContent"=> $ShipmentContent,
                            "Notes"=> $package['remarks'] ?? '',
                        ];
                        $express = new Express($config['au_member_id'],$config['au_password']);
                        $express_no = $express->create($params);
                        $packageAll[] = [
                            'id' => $id,
                            'express_name' => '澳优国际速递',
                            'express_no' => $express_no,
                            'delivertime' => time(),
                            'delivery_status' => 1
                        ];
                        $orderAll[] = [
                            'id' => $package['order_id'],
                            'delivertime' => time(),
                            'state' => 3
                        ];
                        QueueApi::auUploadIdcard([
                            'id' => $id,
                            'shop_id' => $package['shop_id'],
                            'express_no' => $express_no,
                        ],5);
                        QueueApi::auPrint([
                            'id' => $id,
                            'shop_id' => $package['shop_id'],
                        ],5);
                        // 推送消息
                        $this->pushOrder($id,'已发货');
                    }


                }catch (Exception $e){
                    $this->error($e->getMessage());
                }

            }
            model('app\admin\model\wanlshop\Order')->saveAll($orderAll);
            $this->model->saveAll($packageAll);
            $this->success();
        }
        $this->view->assign("lists", $lists); // 可以发货
        $this->view->assign("data", $data); // 不可以发货
        foreach ($brands as $k=>$b){
            if ($b['initial']!='A'){
                unset($brands[$k]);
            }
        }
        $this->view->assign("brands", $brands); // 品 牌列表
        return $this->view->fetch();
    }




    /**
     * 快递查询
     */
    public function relative($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $data = Cache::get($row['express_no'].'_track');
        if(!$data){
            if($row['delivery_mode'] == 'instead'){
                $config = get_addon_config('ymyauexpress');
            }else{
                $config = model('app\index\model\wanlshop\ShopConfig')
                    ->field('au_member_id,au_password')
                    ->where('shop_id',$row['shop_id'])
                    ->find();
            }

            if($row['express_no'][0]=="G"){
                $express = new Expressty();
                $data = $express->track($row['express_no']);
                $data = array_reverse($data);
                Cache::set($row['express_no'].'_track',$data,600);
            }else{
                $express = new Express($config['au_member_id'],$config['au_password']);
                $data = $express->track(['OrderId'=>$row['express_no']]);
                $data = array_reverse($data);
                Cache::set($row['express_no'].'_track',$data,600);
            }


        }
        $list = [];
        $week = array(
            "0"=>"星期日",
            "1"=>"星期一",
            "2"=>"星期二",
            "3"=>"星期三",
            "4"=>"星期四",
            "5"=>"星期五",
            "6"=>"星期六"
        );
        if($data){
            foreach($data as $vo){

                $list[] = [
                    'time' => strtotime($vo['StatusTime']),
                    'status' => '在途'/*$vo['id_OrderStatus']*/, // 1.0.6升级
                    'context' => $vo['StatusDetail'],
                    'week' => $week[date('w', strtotime($vo['StatusTime']))]
                ];
            }
        }else{
            $list = [
                'status' => '已发货',
                'context' => '包裹等待揽收~',
                'time' => date('Y-m-d H:i:s', $row['delivertime'])
            ];
        }
        $this->view->assign("week", $week);
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 打单 & 批量打单
    */
    public function invoice($ids = null)
    {
        $row = $this->model->all($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $print_urls = [];
        foreach ($row as $package) {
            /*if($data['print_url']) {
                $print_urls[] = $data['print_url'];
            }*/
            if($package['delivery_mode'] == 'instead'){
                $shopConfig = get_addon_config('ymyauexpress');;
            }else{
                $shopConfig = model('app\api\model\wanlshop\ShopConfig')->where('shop_id',$package['shop_id'])->find();
            }
            if($package['express_no']){
                $params = [
                    "orderId" => $package['express_no'],
                    "printMode" => 1,
                    "fileType" => 1,
                    "fontSize" => 0,
                ];
                $express = new Express($shopConfig['au_member_id'],$shopConfig['au_password']);
                $ret = $express->print($params);
                if($ret){
                    $package->print_url = $ret;
                    $package->save();
                    $print_urls[] = $ret;
                }
            }

        }
        $this->view->assign("print_urls", $print_urls);
        return $this->view->fetch();
    }
    /**
     * 订单推送消息（方法内使用）
     *
     * @param string order_id 订单ID
     * @param string state 状态
     */
    private function pushOrder($package_id = 0, $state = '已发货')
    {
        $package = $this->model->get($package_id);
        $packageGoods = model('app\admin\model\wanlshop\Packagegoods')
            ->where(['package_id' => $package_id])
            ->select();
        $msgData = [];
        foreach ($packageGoods as $goods) {
            $msg = [
                'user_id' => $package['user_id'], // 推送目标用户
                'shop_id' => $package['shop_id'],
                'title' => '您的包裹'.$state, // 推送标题
                'image' => $goods['image'], // 推送图片
                'content' => '您购买的商品 '.(mb_strlen($goods['title'],'utf8') >= 25 ? mb_substr($goods['title'],0,25,'utf-8').'...' : $goods['title']).' '.$state,
                'type' => 'order',  // 推送类型
                'modules' => 'order',  // 模块类型
                'modules_id' => $package['order_id'],  // 模块ID
                'come' => '包裹'.$package['package_no'] // 来自
            ];
            $msgData[] = $msg;
            $this->wanlchat->send($package['user_id'], $msg);
        }
        $notice = model('app\index\model\wanlshop\Notice')->saveAll($msgData);
    }
}
